const request = require('request');//第三方库
const cherrio = require('cheerio')//第三方库
const mkdirp = require('mkdirp');//第三方库
const express = require('express')//第三方库
const iconV = require('iconv-lite');//第三方库
const schedule = require("node-schedule"); //第三方包（定时任务）
const fs = require('fs');//node自带
const path = require('path');//node自带
const app = express();


/*创建本地用来保存下载下来的图片目录路径和名称*/
const dir = path.join(__dirname + '/img');

/*使用mkdirp包创建目录*/
mkdirp(dir, function (err) {
    if (err) {
        console.log(err);
    }
});

/*这个url是百度图片的接口*/
var url = 'http://image.baidu.com/search/acjson?tn=resultjson_com&catename=pcindexhot&ipn=rj&ct=201326592&word=pcindexhot&rn=30';

function fmtDate() {
    var date = new Date();
    var Y = 1900 + date.getYear();
    var M = "0" + (date.getMonth() + 1);
    var D = "0" + date.getDate();
    var h = (date.getHours()>=10)?date.getHours():'0'+date.getHours();
    var m = (date.getMinutes()>=10)?date.getMinutes():'0'+date.getMinutes();
    var s = (date.getSeconds()>=10)?date.getSeconds():'0'+date.getSeconds();
    return Y + "-" + M.substring(M.length - 2, M.length) + "-" + D.substring(D.length - 2, D.length)+'-'+h+':'+m+':'+s;
}




var rule1 = new schedule.RecurrenceRule();
var times1 = [1, 11, 21, 31, 41, 51];
rule1.second = times1;

schedule.scheduleJob(rule1, function () {
    console.log(fmtDate());
    run()
});

function run() {
    request(url, function (err, response, body) {
        if (!err && response.statusCode == 200) {
            var newBody = JSON.parse(body)
            var data = newBody.data;
            data.pop()

            data.map(function (obj, index) {
                var url = obj.hoverURL;
                var num = url.lastIndexOf('.') - 2
                var imgName = url.substr(num)

                download(url, imgName)
            })
        }
    });

}

//下载图片*/
var download = function (url, imgName) {

    request(url).pipe(fs.createWriteStream(dir + '/' + imgName))


};


